package com.remoter.basic.task.support;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.remoter.basic.bean.support.RemoterRequest;
import com.remoter.basic.bean.support.RemoterResponse;
import com.remoter.basic.configure.IConfiguration;
import com.remoter.basic.configure.support.AbstractConfiguration;
import com.remoter.basic.task.ITask;
import com.remoter.basic.task.ITaskFilter;
import com.remoter.basic.util.Final;
import com.remoter.basic.util.ObjectChain;
import com.remoter.basic.util.ServiceLoader;
import com.remoter.basic.util.StringUtil;

/**
 * @author			koko
 * @date 			2017-08-09 09:23:59
 * @description 	类功能说明
 */
public abstract class AbstractMessgaeTask implements ITask{
	
	protected static final Logger logger = LoggerFactory.getLogger(AbstractMessgaeTask.class);
	
	protected final RemoterRequest remoterRequest;
	protected final RemoterResponse remoterResponse;
	protected final IConfiguration configuration;
	protected final ObjectChain<ITaskFilter> chain;
	
	public AbstractMessgaeTask(RemoterRequest remoterRequest,RemoterResponse remoterResponse){
		this.remoterRequest = remoterRequest;
		this.remoterResponse = remoterResponse;
		this.configuration = AbstractConfiguration.getConfiguration();
		this.chain = new ObjectChain<ITaskFilter>();
		this.initFilter(this.configuration.getOption(Final.O_VAL_FILTER));
	}
	
	@Override
	public Boolean call() throws Exception {
		if(null != this.chain){
			this.chain.rewind();
			if(this.chain.hasNext()){
				this.chain.next().execute(this.remoterRequest,this.remoterResponse,this.chain);
			}
		}
		return true;
	}
	
	protected void initFilter(String filterString){
		if(StringUtil.isBlank(filterString)){
			return;
		}
		String[] filters = filterString.split(Final.D_VAL_SEPARATOR);
		if(null == filters || filters.length == 0){
			return;
		}
		for(String filter : filters){
			if(StringUtil.isBlank(filter)){
				logger.warn("ITaskFilter name is empty !");
			}else{
				ITaskFilter f = ServiceLoader.getService(ITaskFilter.class,filter);
				if(null == f){
					logger.warn("ITaskFilter not found : "+filter);
				}else{
					this.chain.add(f);
					logger.debug("ITaskFilter add success : " + filter);
				}
			}
		}
	}
	
}